// app.js
App({
  request(options) {
    let that = this;
    let {
      url,
      data,
      params,
      method,
      loading
    } = options;
    // if (loading) {
      wx.showLoading({
        title: "加载中",
      });
    // }
    return new Promise((resolve, reject) => {
      console.log("发送给" + url + "的数据为:", data);
      let query = "";
      if (params && Object.keys(params).length > 0) {
        query = "?";
        for (let key in params) {
          query += key + "=" + params[key] + "&";
        }
        query = query.substr(0, query.length - 1);
      }
      let header = {
        "content-type": "application/json"
      };
      // let token = this.globalData.token;
      // if (token) {
      //   header["Authorization"] = token;
      // }
      let session_id = wx.getStorageSync('session_id')
      if (session_id) {
        header["Cookie"] = session_id;
      }
      wx.request({
        url: that.globalData.apiUrl + url + query, //仅为示例，并非真实的接口地址
        data: data || "",
        method: method || "POST",
        header,
        success(res) {
          // console.log(url + "返回的数据为:", res);
          if(res.statusCode == 200 && url == '/api/user/login'){
            wx.setStorageSync('session_id',res.cookies[0])
          }
          if (res.data.status_code == 0) {
            wx.hideLoading();
            resolve(res.data);
          } else {
            console.log(res.data.msg );
            wx.hideLoading();
            wx.showToast({
              title: "网络异常，请稍后再试",
              icon: "none",
            });
            reject();
          }
        },
        fail(err) {
          console.log(err);
          wx.hideLoading();
          wx.showToast({
            title: err.msg || "接口故障",
            icon: "none",
          });
          reject();
        },
      });
    })
  },

  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('展示用户信息',res)
        // this.setData({
        //   userInfo: res.userInfo,
        //   hasUserInfo: true
        // })
      }
    })
  },
  
  onLaunch() {
    // this.getUserProfile()
  
  },
  globalData: {
    userInfo: null,
    // baseUrl: "http://139.199.173.207/",
    baseUrl: "https://tototalk.chat/",
    socketUrl: "wss://tototalk.chat/api/chat/start",
    // apiUrl: "http://139.199.173.207",
    apiUrl: "https://tototalk.chat",
    appid:'wx77fcb3606cfab715',
    isLogin:false
  },
});